<template>
  <div class="allwork_box">
    <el-page-header @back="goback" content="所有作品" class="allwork_title">
    </el-page-header>
    <div class="table_box">
      <div class="allTeam_h1">
        <h1>{{gameName}}</h1>
      </div>
      <el-table
          v-loading="loading"
          :data="entry"
          border
          style="margin: 40px auto">
<!--        <el-table-column-->
<!--            label="比赛名称"-->
<!--            align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ scope.row.gameName }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
            label="队名"
            align="center">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.groupName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="作品名称"
            align="center">
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.workName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="作品状态"
            align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.workStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="总分"
            align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.averageScore">努力评审中</span>
            <span>{{ scope.row.averageScore }}</span>
          </template>
        </el-table-column>
        <el-table-column
            label="排名"
            align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.ranking">暂无排名</span>
            <span>{{ scope.row.ranking }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
<!--          <template slot="header">-->
<!--            <el-input-->
<!--                v-model="search"-->
<!--                size="mini"-->
<!--                placeholder="输入关键字搜索"/>-->
<!--          </template>-->
          <template slot-scope="scope">
            <el-button
                v-show="score"
                type="success"
                size="medium"
                @click="uploading(scope.$index, scope.row)">评分</el-button>
            <el-button
                type="primary"
                size="medium"
                @click="download(scope.$index, scope.row)">下载作品</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="judges_download">
        <el-button icon="el-icon-download" type="success" size="max" @click="handleDown2"> 下载表格</el-button>
      </div>
    </div>
    <el-dialog title="评分" :visible.sync="showSetScore">
      <el-form :model="Fraction" ref="Fraction" :rules="rules">
        <el-form-item label="项目书得分" label-width="120px" prop="book">
          <el-input v-model="Fraction.book" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="ppt得分" label-width="120px" prop="ppt">
          <el-input v-model="Fraction.ppt" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="答辩得分" label-width="120px" prop="reply">
          <el-input v-model="Fraction.reply" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="unSubmit">取 消</el-button>
        <el-button type="primary" @click="submitScort">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "allwork",
  data() {
    // 分数表单验证
    var checkBook = (rule, value, callback) => {
      if(value>40 || value<0) {
        callback(new Error('必须为0~40之间的整数'));
      }
    };

    var checkOther = (rule, value, callback) => {
      if(value>30 || value<0) {
        callback(new Error('必须为0~30之间的整数'));
      }
    };

    return{
      search: '',//表单搜索
      gameName: window.sessionStorage.getItem('gameName'),
      entry:[],
      work:{},
      teacher: [],
      groupID: [],
      loading: true,
      score: true,
      showSetScore: false, //控制打分表单
      Fraction: {
        groupID: '',
        book: 0,//项目计划书分数
        ppt: 0, //ppt分数
        reply: 0,//答辩分数
        score: 0//总分
      }, //分数
      rules:{
        book:[{ required: true, message: '得分不能为空'},
        { validator: checkBook, trigger: 'blur' }],
        ppt: [{ required: true, message: '得分不能为空'},
          { validator: checkOther, trigger: 'blur' }],
        reply: [{ required: true, message: '得分不能为空'},
          { validator: checkOther, trigger: 'blur' }]
      }
    }
  },
  methods: {
    //生成表格
    async handleDown2(){
      const gameID = {gameID: window.sessionStorage.getItem('gameID')};
      const res = await this.$api.downloadRanks(gameID);
      let a = document.createElement('a');
      a.href = res;
      a.click();
    },

    goback() {
      window.sessionStorage.removeItem('gameID');
      window.sessionStorage.removeItem('groupIDList');
      window.sessionStorage.removeItem('gameName');
      this.$router.push('/backIndex/managementTeam')
    },
    // 评分
    unSubmit() {
      this.showSetScore = false;
      this.$message.warning('已取消');
    },

    async submitScort() {
      this.showSetScore = false;

      this.Fraction.score = parseFloat(this.Fraction.book) + parseFloat(this.Fraction.ppt) + parseFloat(this.Fraction.reply);
      const data = {
        groupID:this.Fraction.groupID.toString(),
        ppt:this.Fraction.ppt.toString(),
        book:this.Fraction.book.toString(),
        reply:this.Fraction.reply.toString(),
        score:this.Fraction.score.toString()
      }
      console.log("提交的：",data);
      const res = await this.$api.judgeScore(data);
      if(res.success){
        this.$message.success("评分成功");
      } else {
        this.$message.error("服务器繁忙，请稍后重试！");
      }

    },
    async uploading(index, row) {
      const showGameID = window.sessionStorage.getItem('gameID');
      if(row.workStatus === '作品已上传' || showGameID==='7'){
        // const data = {groupID:row.groupID};
        // this.$prompt('请输入你的评分', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   inputPattern: /^(0|[1-9]\d?|100)$/,
        //   inputErrorMessage: '请输入0~100之间的整数'
        // }).then(async ({ value }) => {
        //   data.score = value;
        //   const res = await this.$api.judgeScore(data);
        //   if(res.success){
        //     this.$message({
        //       type: 'success',
        //       message: '成功评分：'+ value + '分'
        //     });
        //   } else {
        //     return this.$message.warning(res.message)
        //   }
        // }).catch(() => {
        //   this.$message({
        //     type: 'info',
        //     message: '取消输入'
        //   });
        // });
        const data = {groupID:row.groupID};
        this.showSetScore = true;
        const res = await this.$api.getJudgeLine(data);
        this.Fraction.book = res.book;
        this.Fraction.ppt = res.ppt;
        this.Fraction.reply = res.reply;
        this.Fraction.groupID = row.groupID;
      } else {
        this.$alert('无法评分！', '作品未上传', {
          confirmButtonText: '确定',
          callback: ()=> {
            this.$message({
              type: 'info',
              message: '评分失败'
            });
          }
        });
      }

    },

    //  通过groupID获取参赛小组信息
    async getGroup(data){
      const gruopID = {groupID:data};
      const tableAllData = await this.$api.getgroups(data);
      let temp = tableAllData.data.getInfo;
      const teachers = await this.$api.getGroupTeacherInfo(data)
      temp.teacher = teachers.data.getGroupTeacherInfo;
      this.teacher = teachers.data.getGroupTeacherInfo;
      const work = await this.$api.getWorkInfo(data);
      if(work.data.work.title === null){
        temp.workName = '作品名称未提交';
      }else {
        temp.workName = work.data.work.title;
        temp.workurl = work.data.work.attachment;
      }
      this.work = work.data.work;
      const JudgeLine = await this.$api.getJudgeLine(gruopID);
      this.Fraction = {...JudgeLine}
      const workStatus = await this.$api.getWorkStatus(gruopID); //作品状态
      temp.workStatus = workStatus;
      const ranking = await this.$api.getRanking(gruopID);
      if(temp.workStatus === '作品已上传' && ranking.data.status === '您的评分已结束'){
        temp.ranking = ranking.data['yourRanks:'];
        temp.averageScore = ranking.data.averageScore;
      }
      this.entry.push(temp);
      this.entry.sort(this.sortBy('ranking', 'groupID'));
    },

    //排序算法
    sortBy(field1,field2) {
      return function(a,b) {
        if(a[field1] === b[field1] || a[field1] === undefined || b[field1] === undefined) return a[field2] - b[field2];
        return a[field1] - b[field1];
      }
    },


    //  获取自己参加的比赛
    async getOwnSignup() {
      this.loading = true;
      const res = JSON.parse(window.sessionStorage.getItem('groupIDList'));
      const a = typeof res;
      if(a === 'object'){
        this.groupID = res;
      }
      await this.groupID.forEach(temp => {
        this.getGroup(temp);
      });
      setTimeout(()=> {
      this.loading = false;
    },13000);
    },

    // 下载
    download(index, row) {
      if(row.workurl){
        let a = document.createElement('a');
        a.href = row.workurl;
        a.click();
      } else {
        this.$notify.error({
          title: '错误',
          message: '作品未上传！',
          duration: 2000,
          showClose: false
        });
      }
    }
  },
  mounted() {
    this.getOwnSignup();
    if(window.sessionStorage.getItem('level') === '3'){
      this.score = true;
    } else {
      this.score = false;
    }
  }
}
</script>

<style lang="less" scoped>
.allwork_box{
  .allwork_title{
    margin-bottom: 20px;
  }
  .table_box{
    .allTeam_h1{
      text-align: center;
      font-size: 20px;
      font-weight: bolder;
    }
    background-color: #ffff;
    padding: 40px;
    box-shadow: 0 2px 7px rgba(187, 172, 172, 0.49), 0 5px 11px rgba(247, 231, 231, 0.36);
  }
}
</style>
